import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {ChannelOccupy, CommodityStatus, DeviceStatus, UserType} from '../../../../../used-store/used-store-manage.pipe';
import {UsedStorePService} from '../../../../../used-store/used-store-p.service';
import {UsedStoreZservice} from '../../../../../used-store/used-store-zservice';
import {moveItemInArray} from '@angular/cdk/drag-drop';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-decoration-used-goods',
  templateUrl: './used-goods.component.html',
  styleUrls: ['./used-goods.component.scss']
})
export class UsedGoodsComponent implements OnInit {
  @Input() componentData: any; // 原始数据
  @Output() save = new EventEmitter(); // 保存修改
  @Output() closeComponent = new EventEmitter(); // 关闭
  componentNameDisabled = false; // 组件名输入框禁用状态
  DEVICESTATUS = DeviceStatus;
  CHANNELOCCUPY = ChannelOccupy;
  COMMODITYSTATUS = CommodityStatus;
  USERTYPE = UserType;
  query = {
    equipmentCode: '', // 编码
    typeId: [], // 设备品牌
    modelId: [], // 设备型号
    status: [], // 状态
    userType: [], // 适用用户
    colourB: [], // B端成色
    colourC: [], // C端成色
    libraryId: [], // 库位
    clinchTime: null, // 成交入库时间
    up: null, // 上架时间
    page: 1, // 当前页
    pageSize: 10, // 分页大小
  };
  listOfData = {
    total: 0,
    records: []
  };
  // 品牌待选项
  brandOptions: any[] = [];
  // 机型待选项
  typeOptions: any[] = [];
  // 库位待选项
  locationOptions: any[] = [];
  // 成色待选项
  colourBOptions: any[] = [];
  colourOptions: any[] = [];
  goodsModal = {
    visible: false,
    ids: new Set()
  };
  setOfCheckedId = new Set();
  checked = false;
  indeterminate = false;


  constructor(
    private usedStorePService: UsedStorePService,
    private usedStoreZservice: UsedStoreZservice,
    private nzMessageService: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.componentNameDisabled = !!this.componentData?.name;
  }

  saveBtn() {
    if (!this.componentData.content.length) {
      this.nzMessageService.error('至少需要一条数据');
      return;
    }
    this.save.emit(this.componentData);
  }

  drop(event: any) {
    moveItemInArray(this.componentData.content, event.previousIndex, event.currentIndex);
  }

  removeItem(index: number) {
    this.componentData.content.splice(index, 1);
  }

  addDevice() {
    this.componentData.content.push(...Array.from(this.setOfCheckedId).map(id => ({id})));
    this.hideGoodsModal();
  }


  queryBtn() {
    this.query.page = 1;
    this.queryList();
  }

  resetQuery() {
    this.query = {
      equipmentCode: '', // 编码
      typeId: [], // 设备品牌
      modelId: [], // 设备型号
      status: [], // 状态
      userType: [], // 适用用户
      colourB: [], // B端成色
      colourC: [], // C端成色
      libraryId: [], // 库位
      clinchTime: null, // 成交入库时间
      up: null, // 上架时间
      page: 1, // 当前页
      pageSize: 10, // 分页大小
    };
    this.queryList();
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.queryList();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.queryList();
  }

  // 查询列表
  queryList(): void {
    this.usedStorePService.getCommodityList({
      ...this.query,
      // @ts-ignore
      createTime: this.usedStorePService.formatTime(this.query.up ? this.query.up[0] : '', 'date'),
      // @ts-ignore
      endTime: this.usedStorePService.formatTime(this.query.up ? this.query.up[1] : '', 'date'),
      // @ts-ignore
      clinchTime: this.usedStorePService.formatTime(this.query.clinchTime ? this.query.clinchTime[0] : '', 'date'),
      // @ts-ignore
      clinchEndTime: this.usedStorePService.formatTime(this.query.clinchTime ? this.query.clinchTime[1] : '', 'date'),
      typeId: this.query.typeId.join(','),
      modelId: this.query.modelId.join(','),
      status: this.query.status.join(','),
      userType: this.query.userType.join(','),
      colourIdB: this.query.colourB.join(','),
      colourId: this.query.colourC.join(','),
      libraryId: this.query.libraryId.join(','),
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
    });
  }

  getTypeList() {
    this.query.modelId = [];
    if (!this.query.typeId.join(',')) {
      this.typeOptions = [];
      return;
    }
    this.usedStorePService.getTypeList(this.query.typeId.join(',')).then((res: any) => {
      if (res.code === 0) {
        this.typeOptions = res.data.records;
      }
    });
  }

  async showGoodsModal() {
    await this.usedStorePService.dictData('machine_condition').then((res: any) => {
      if (res.code === 0) {
        this.colourOptions = res.data.list.records;
      }
    });
    await this.usedStorePService.dictData('machine_condition_b').then((res: any) => {
      if (res.code === 0) {
        this.colourBOptions = res.data.list.records;
      }
    });
    await this.usedStoreZservice.recycleLibraryList({page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.locationOptions = res.data.records;
      }
    });
    await this.usedStorePService.getBrandList().then((res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.records;
      }
    });
    this.queryList();
    this.goodsModal = {
      visible: true,
      ids: new Set(Array.from(this.componentData.content.map((item: any) => item.id)))
    };
  }

  onAllChecked(checked: boolean) {
    this.listOfData.records.filter((item: any) => !this.goodsModal.ids.has(item.id))
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }

  updateCheckedSet(id: number, checked: boolean) {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  refreshCheckedStatus() {
    this.checked = this.listOfData.records.every(({id}) => this.setOfCheckedId.has(id));
    this.indeterminate = this.listOfData.records.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }



  hideGoodsModal() {
    this.query = {
      equipmentCode: '', // 编码
      typeId: [], // 设备品牌
      modelId: [], // 设备型号
      status: [], // 状态
      userType: [], // 适用用户
      colourB: [], // B端成色
      colourC: [], // C端成色
      libraryId: [], // 库位
      clinchTime: null, // 成交入库时间
      up: null, // 上架时间
      page: 1, // 当前页
      pageSize: 10, // 分页大小
    };
    this.listOfData = {
      total: 0,
      records: []
    };
    this.goodsModal = {
      visible: false,
      ids: new Set()
    };
    this.setOfCheckedId = new Set();
    this.checked = false;
    this.indeterminate = false;
  }
}
